// AdminProductPage.js
import strHtml from "./AdminProductPage.html"; // 使用 raw-loader 加载 HTML 文件
import { DomUtils } from "../../utils/DomUtils"; // 引入 DomUtils 类
import { BasePage } from "../BacePage"; // 引入 BacePage 类
import { productService } from "../../services/productService";
import { fetchUsers } from "../../services/api";

export class AdminProductPage extends BasePage {
  constructor() {
    super();
    this.dom = null;
    this.productList = [];
    this.table = null;
    this.productModal = null;
    this.deleteConfirmModal = null;
    this.pendingDeleteId = null;
    this.uploadedImage = null;
  }

  async render() {
    this.dom = DomUtils.convertToDom(strHtml);
    this._bindEvents();
    await this._loadData();
    this._initDataTable();
    return this.dom;
  }

  async _loadData() {
    try {
      const [products, users] = await Promise.all([
        productService.getAll(),
        fetchUsers(),
      ]);
      // 用户列表转map
      const userMap = {};
      users.forEach((u) => {
        userMap[u.userId] = u.username;
      });
      this.productList = products.map((p) => ({
        ...p,
        userName: p.user ? userMap[p.user.userId] || "-" : "-",
      }));
    } catch (error) {
      console.error("加载产品或用户数据失败:", error);
      this.productList = [];
    }
  }

  _bindEvents() {
    const form = this.dom.querySelector("#productForm");
    this.productModal = new bootstrap.Modal(
      this.dom.querySelector("#productModal")
    );
    this.deleteConfirmModal = new bootstrap.Modal(
      this.dom.querySelector("#deleteConfirmModal")
    );

    // 本地上传并压缩
    this.dom
      .querySelector("#productImage")
      .addEventListener("change", async (e) => {
        const file = e.target.files[0];
        if (file) {
          const base64 = await this._compressImageToBase64(file);
          this.uploadedImage = base64;
          const preview = this.dom.querySelector("#imagePreview");
          preview.src = base64;
          preview.style.display = "block";
        }
      });

    this.dom
      .querySelector("#saveProductBtn")
      .addEventListener("click", async () => {
        const id = form.querySelector("#productId").value;
        const image =
          this.uploadedImage || form.querySelector("#imagePreview").src;
        const currentUser = JSON.parse(
          localStorage.getItem("currentUser") || "{}"
        );
        const userId = currentUser.userId;
        const product = {
          productName: form.querySelector("#productName").value,
          productImageUrl: image,
          productionDate: form.querySelector("#productionDate").value,
          productionPeriod: form.querySelector("#productionPeriod").value,
          productionPlace: form.querySelector("#productionPlace").value,
          category: form.querySelector("#category").value,
          productPrice:
            parseFloat(form.querySelector("#productPrice").value) || 0,
          stock: parseInt(form.querySelector("#stock").value) || 0,
          userId: userId,
        };

        if (id) {
          await this._handleUpdateProduct(id, product);
        } else {
          await this._handleCreateProduct(product);
        }
      });

    this.dom
      .querySelector("#confirmDeleteBtn")
      .addEventListener("click", async () => {
        if (this.pendingDeleteId) {
          await this._handleDeleteProduct(this.pendingDeleteId);
          this.pendingDeleteId = null;
          this.deleteConfirmModal.hide();
          await this._loadData();
          this._refreshTable();
        }
      });
  }

  _initDataTable() {
    this.table = window
      .$(this.dom.querySelector("#product-datatable"))
      .DataTable({
        data: this.productList,
        destroy: true,
        lengthChange: false,
        searching: true,
        pageLength: 10,
        columns: [
          {
            data: "productImageUrl",
            render: (url) => {
              if (!url) return "";
              if (!url.startsWith("data:image")) {
                return `<img src="data:image/png;base64,${url}" width="60" height="40" alt="图"/>`;
              }
              return `<img src="${url}" width="60" height="40" alt="图"/>`;
            },
          },
          {
            data: "productName",
            render: (name, _, row) =>
              `<span class="text-primary clickable" data-id="${row.productId}">${name}</span>`,
          },
          {
            data: "userName",
            render: (userName) => userName || "-",
          },
          { data: "productionDate" },
          { data: "productionPeriod" },
          { data: "productionPlace" },
          {
            data: "category",
            render: (cat) => {
              if (cat === "fruit") return "水果";
              if (cat === "vegetable") return "蔬菜";
              return cat || "";
            },
          },
          {
            data: "productPrice",
            render: (price) => `￥${(price || 0).toFixed(2)}`,
          },
          {
            data: "stock",
            render: (stock) =>
              `<span class="badge ${stock > 0 ? "bg-success" : "bg-danger"}">${
                stock > 0 ? stock : "已售罄"
              }</span>`,
          },
          { data: "clickCount" },
          {
            data: "status",
            render: (status, _, row) =>
              `<button class="btn btn-sm ${
                status === "上架" ? "btn-secondary" : "btn-success"
              } btn-toggle" data-id="${row.productId}">
              ${status === "上架" ? "下架" : "上架"}
            </button>`,
          },
          {
            data: null,
            orderable: false,
            render: (_, __, row) =>
              `<button class="btn btn-sm btn-danger btn-delete" data-id="${row.productId}">删除</button>`,
          },
        ],
      });

    this._bindRowEvents();
  }

  _refreshTable() {
    this.table.clear().rows.add(this.productList).draw();
    this._bindRowEvents();
  }

  _bindRowEvents() {
    const form = this.dom.querySelector("#productForm");
    setTimeout(() => {
      this.dom.querySelectorAll(".btn-delete").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          this.pendingDeleteId = e.target.dataset.id;
          this.deleteConfirmModal.show();
        });
      });
      this.dom.querySelectorAll(".btn-toggle").forEach((btn) => {
        btn.addEventListener("click", (e) => {
          const id = e.target.dataset.id;
          this._handleToggleStatus(id);
        });
      });
      this.dom.querySelectorAll(".clickable").forEach((el) => {
        el.addEventListener("click", async (e) => {
          const id = e.target.dataset.id;
          await this._handleIncrementClickCount(id);
        });
      });
    }, 0);
  }

  // 压缩图片为 base64（最大宽度 300px，质量 0.7）
  _compressImageToBase64(file, maxWidth = 300) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (event) => {
        const img = new Image();
        img.onload = () => {
          const scale = maxWidth / img.width;
          const canvas = document.createElement("canvas");
          canvas.width = maxWidth;
          canvas.height = img.height * scale;
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          const compressedBase64 = canvas.toDataURL("image/jpeg", 0.7);
          resolve(compressedBase64);
        };
        img.src = event.target.result;
      };
      reader.readAsDataURL(file);
    });
  }
}
